package hero.niofile;

import java.nio.charset.Charset;
import java.nio.ByteBuffer;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class FileCopy {

    public static void main(String[] args) throws Exception {
        readFile();
    }

    public static void copy() throws IOException{
        FileInputStream inFile = new FileInputStream("test.txt");
        FileOutputStream outFile = new FileOutputStream("test2.txt");
        FileChannel inChannel = inFile.getChannel();
        FileChannel outChannel = outFile.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024*1024);
        while (true ) {
            int n = inChannel.read(buffer) ;
            if (n== -1 ) break;
            buffer.flip();
            while (buffer.hasRemaining()) {
                outChannel.write(buffer);
            }
            buffer.clear();
        }
        inChannel.close();
        outChannel.close();
        System.out.println("finished");
    }

    public static void transfer() throws Exception {
        FileInputStream inFile = new FileInputStream("test.txt");
        FileOutputStream outFile = new FileOutputStream("test2.txt");
        FileChannel inChannel = inFile.getChannel();
        FileChannel outChannel = outFile.getChannel();
        inChannel.transferTo(0,inChannel.size(),outChannel);
    }

    public static void writeFile() throws Exception {
        FileOutputStream outFile = new FileOutputStream("test2.txt");
        FileChannel outChannel = outFile.getChannel();
        ByteBuffer buf =ByteBuffer.wrap("错觉3".getBytes("GBK"));
        outChannel.write(buf);
        outChannel.close();
    }

    public static void readFile() throws Exception {
        FileInputStream inFile = new FileInputStream("test2.txt");
        FileChannel inChannel = inFile.getChannel();
        ByteBuffer buf = ByteBuffer.allocate((int)inChannel.size());
        inChannel.read(buf);
        buf.flip();
        Charset charset = Charset.forName("GBK");
        System.out.println(charset.decode(buf));
        inChannel.close();
    }

}
